package com.metro.outsourced.filemng.handler;

import cn.hutool.core.io.FileUtil;
import com.metro.outsourced.filemng.entity.FileRecordEntity;
import com.metro.outsourced.filemng.service.impl.FileRecordServiceImpl;
import com.metro.outsourced.filemng.utils.GzbZipUtil;
import com.metro.outsourced.filemng.vo.FileRecordVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 文件处理器
 */
@Component
@Slf4j
public class FileHandler {

    @Resource
    private FileRecordServiceImpl fileRecordService;

    /**
     * 上传ZIP文件并解压
     *
     * @param file 文件
     * @param prefixPath 前缀
     * @return zip解压后文件信息列表
     */
    public List<FileRecordVO> uploadZip(MultipartFile file, String prefixPath) {
        if (file == null) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String dataStr = sdf.format(new Date());
        String zipFilePath = prefixPath + "/" + dataStr + "/" +file.getOriginalFilename();
        List<FileRecordVO> recordVOS = new ArrayList<>();
        File uploadZipfile = null;
        try {
            List<FileRecordEntity> records = new ArrayList<>();
            FileUtil.writeBytes(file.getBytes(), zipFilePath);
            uploadZipfile = new File(zipFilePath);

            String unzipDirName = "unzip/"  + UUID.randomUUID().toString().replaceAll("-", "");
            GzbZipUtil.unzip(uploadZipfile, Charset.forName("GBK"), unzipDirName);
            File unzipFile = new File(prefixPath + "/" + dataStr + "/"   + unzipDirName);
            File[] files = unzipFile.listFiles();
            if (files != null) {
                for (File f : files) {
                    String filePath = f.getPath();
                    FileRecordEntity fileRecord = new FileRecordEntity(filePath, f.getName(), UUID.randomUUID().toString().replaceAll("-", ""));
                    records.add(fileRecord);
                }
            }
            fileRecordService.saveBatch(records);
            for (FileRecordEntity record : records) {
                FileRecordVO recordVO = new FileRecordVO();
                BeanUtils.copyProperties(record,recordVO);
                recordVOS.add(recordVO);
            }
        } catch (Exception e) {
            log.error("上传压缩文件异常！！{}",e.getMessage());
        }finally {
            if(uploadZipfile != null && uploadZipfile.exists()){
                boolean isDelete = uploadZipfile.delete();
                if (isDelete) {
                    log.info("uploadZipFile上传文件删除成功");
                } else {
                    log.info("uploadZipFile 上传文件删除失败");
                }

            }
        }
        return recordVOS;
    }

    /**
     * @param file       文件
     * @param objId      业务ID(可选)
     * @param prefixPath 文件路径前缀
     * @return 文件信息
     */
    public FileRecordVO uploadFile(MultipartFile file, String objId, String prefixPath) {
        if (file == null) {
            return null;
        }
        String fileName = file.getOriginalFilename();
        if (StringUtils.isEmpty(objId)) {
            objId = UUID.randomUUID().toString().replaceAll("-", "");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String dataStr = sdf.format(new Date());
        String filePath = prefixPath + "/" + dataStr + "/" + file.getOriginalFilename();
        try {
            FileUtil.writeBytes(file.getBytes(), filePath);
            FileRecordEntity fileRecord = new FileRecordEntity(filePath, fileName, objId);
            fileRecordService.save(fileRecord);
        } catch (Exception e) {
            log.error("上传文件异常：{}",e.getMessage());
        }

        return new FileRecordVO(filePath, fileName, objId);
    }

    /**
     * 获取文件信息
     * @param objId 业务Id
     * @return
     */
    public FileRecordVO getFileInfo(String objId){
        return fileRecordService.getInfo(objId);
    }

    /**
     * 删除文件
     * @param objId 业务Id
     * @return
     */
    public boolean delFile(String objId){
        FileRecordVO vo = fileRecordService.getInfo(objId);
        if(vo == null){
            return false;
        }else {
            fileRecordService.delFile(objId);
            File file = new File(vo.getFilePath());
            if(file.exists()){
                boolean delete = file.delete();
                if (delete) {
                    log.info("文件删除成功！");
                } else {
                    log.info("文件删除失败！");
                }
            }
        }
        return true;
    }
}
